package resources;

import java.io.BufferedWriter;
import java.io.FileWriter;


public class Logger {
	private static volatile Logger instance;
	StringBuilder log;
	
	private Logger(){
		log = new StringBuilder();
	}

	// This method is called getInstance. It uses a double - locking mechanism
	// to ensure
	// synchronization between threads when accessed so that no more than one
	// instance is created.
	// Finally the instance of the single List of records is returned.
	public static Logger getInstance() {
		if (instance == null) {
			synchronized (Logger.class) {
				if (instance == null)
					instance = new Logger();
			}
		}
		return instance;
	}
	
	public synchronized void addToLog(String s){
		log.append(s);
		log.append("\n");
	}
	
	public synchronized String getLog(){return log.toString();}
	
	public void reset(){
		log = new StringBuilder();
	}
	
	public void writeToFile(String fileName){
		  try{
			    // Create file 
			    FileWriter fstream = new FileWriter(fileName);
			        BufferedWriter out = new BufferedWriter(fstream);
			    out.write(log.toString());
			    //Close the output stream
			    out.close();
			    }catch (Exception e){//Catch exception if any
			      System.err.println("Error: " + e.getMessage());
			    }
	}
}
